package com.orchard.orchardfarmmanagementsystem.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class TokenUtil {

    private static final Map<String, TokenEntry> tokenStore = new HashMap<>();
    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 24; // Token 有效期为1小时（毫秒）

    private static class TokenEntry {
        String username;
        long creationTime;

        public TokenEntry(String username) {
            this.username = username;
            this.creationTime = System.currentTimeMillis();
        }
    }

    public static String generateToken(String username) {
        String token = UUID.randomUUID().toString();
        tokenStore.put(token, new TokenEntry(username));
        return token;
    }

    public static String getUsernameFromToken(String token) {
        TokenEntry entry = tokenStore.get(token);
        if (entry != null && !isTokenExpired(entry)) {
            return entry.username;
        }
        return null;
    }

    public static boolean validateToken(String token) {
        TokenEntry entry = tokenStore.get(token);
        return entry != null && !isTokenExpired(entry);
    }

    private static boolean isTokenExpired(TokenEntry entry) {
        long currentTime = System.currentTimeMillis();
        return (currentTime - entry.creationTime) > EXPIRATION_TIME;
    }

    public static void expireToken(String token) {
        TokenEntry entry = tokenStore.get(token);
        if (entry != null) {
            // 将创建时间设置为远过去的时间点，确保它总是被认为已经过期
            entry.creationTime = System.currentTimeMillis() - (EXPIRATION_TIME + 1);
            // 或者直接从 tokenStore 中移除该 Token
            // tokenStore.remove(token);
        }
    }
}